var crypto = require('crypto');
var wxconfig = require('./wxconfig');
var get = require('./get.js');
var post = require('./post.js');
var raw = function (args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });
  var string = '';
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k];
  }
  string = string.substr(1);
  return string;
}
/**
* @synopsis 签名算法 
*
* @param jsapi_ticket 用于签名的 jsapi_ticket
* @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
*
* @returns
*/
var WxApi = {
    getXMLNodeResultValue: function(node_name, xml) {  
        var tmp = xml.split("<" + node_name + ">");  
        var _tmp = tmp[1].split("</" + node_name + ">"); 
        var node_value = _tmp[0];
        var value = node_value.split('[');
        var _value = value[2].split(']');
        return _value[0];  
    },
    getXMLNodeValue: function(node_name, xml) {  
        var tmp = xml.split("<" + node_name + ">");  
        var _tmp = tmp[1].split("</" + node_name + ">");  
        return _tmp[0];  
    },
    createNonceStr:function () {
      return Math.random().toString(36).substr(2, 15);
    },
    createTimestamp:function () {
      return parseInt(new Date().getTime() / 1000) + '';
    },
    create_sign:function(jsapi_ticket, url){
        var ret = {
          jsapi_ticket: jsapi_ticket,
          nonceStr: this.createNonceStr(),
          timestamp: this.createTimestamp(),
          url: url
        };
        var string = raw(ret);
            jsSHA = require('jssha');
            shaObj = new jsSHA(string, 'TEXT');
        ret.signature = shaObj.getHash('SHA-1', 'HEX');
        return ret;
      },
    //签名sign的统一生成
    public_sign:function(ret){
      var string = raw(ret);
      var key = wxconfig.key;
      string = string + '&key='+key;  //key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置      
      var sign_str  = crypto.createHash('md5').update(string,'utf8').digest('hex');      
      return sign_str.toUpperCase();
    },
    // 统一下单接口
    wx_unifiedorder:function(trade_type,spbill_create_ip,out_trade_no,cb){
      if (out_trade_no == null || out_trade_no == '') {
          return;
      }
      var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
      // var host = "192.168.1.237";
      var path = "/pay/unifiedorder";
      var ret = {
            appid: wxconfig.appid,
            attach: wxconfig.attach,
            body: wxconfig.body,
            mch_id: wxconfig.mch_id,
            nonce_str: this.createNonceStr(),
            notify_url: wxconfig.notify_url,
            // openid:'',
            product_id:'12345',
            out_trade_no:out_trade_no,
            total_fee:wxconfig.total_fee
      };
      ret.spbill_create_ip = spbill_create_ip;
      ret.trade_type = trade_type;//NATIVE:扫码支付  
      var sign = this.public_sign(ret);
      var formData = "<xml>";
      formData += "<appid>"+ret.appid+"</appid>"; //appid
      formData += "<attach>"+ret.attach+"</attach>"; //附加数据
      formData += "<body>"+ret.body+"</body>"; //商品或支付单简要描述
      formData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      formData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      formData += "<notify_url>"+ret.notify_url+"</notify_url>"; //支付成功后微信服务器通过POST请求通知这个地址
      formData += "<product_id>"+ret.product_id+"</product_id>"; //扫码支付这个参数不是必须的
      formData += "<out_trade_no>"+ret.out_trade_no+"</out_trade_no>"; //订单号
      formData += "<spbill_create_ip>"+ret.spbill_create_ip+"</spbill_create_ip>"; //不是必须的
      formData += "<total_fee>"+ret.total_fee+"</total_fee>"; //金额
      formData += "<trade_type>"+ret.trade_type+"</trade_type>"; //NATIVE会返回code_url ，JSAPI不会返回
      formData += "<sign>" + sign + "</sign>";
      formData += "</xml>";
      post.https_post(formData,wxconfig.host,wxconfig.port,path,function(ret,body){
         if (ret == 200 && cb != null){
              cb(body,sign,ret);
         }
      });
    },
    // 查询订单接口
    wx_orderquery:function(out_trade_no,transaction_id,cb){
      // 推荐使用微信订单号：transaction_id
      if ((out_trade_no == null || out_trade_no == '') && 
          (transaction_id == null || transaction_id == '')){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/pay/orderquery'; 
      var path = "/pay/orderquery";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          transaction_id:transaction_id,
          out_trade_no:'',
          nonce_str:this.createNonceStr()
      };
      console.log(ret);
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<transaction_id>"+ret.transaction_id+"</transaction_id>"; //订单号
      xmlData += "<out_trade_no>"+ret.out_trade_no+"</out_trade_no>"; //订单号
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "<sign_type>MD5</sign_type>";
      xmlData += "</xml>";
      console.log(xmlData);
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          if (ret == 200 && cb!=null){
            cb(body,sign,ret);
          }
      });
    },
    // 关闭订单接口
    wx_closeorder:function(out_trade_no,cb){
      if (out_trade_no == null || out_trade_no == '') {
        return;
      }
       var url = 'https://api.mch.weixin.qq.com/pay/closeorder';
       var path = '/pay/closeorder';
       var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          out_trade_no:out_trade_no,
          nonce_str:this.createNonceStr()
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<out_trade_no>"+ret.out_trade_no+"</out_trade_no>"; //订单号
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "<sign_type>MD5</sign_type>";
      xmlData += "</xml>";
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          if (ret == 200 && cb!=null){
            cb(body,sign,ret);
          }
      });
    },
    // 企业向用户零钱付款：需要证书
    wx_lingqian:function(partner_trade_no, openid, spbill_create_ip, cb){
       var url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
       var path = '/mmpaymkttransfers/promotion/transfers';
       var ret = {
           mch_appid:wxconfig.appid,
           mchid:wxconfig.mch_id,
           nonce_str:this.createNonceStr(),
           partner_trade_no:partner_trade_no,
           openid:openid,
           check_name:'NO_CHECK',
           re_user_name:'闵亚楠',
           amount:100,
           desc:'提现',
           spbill_create_ip:spbill_create_ip
       };
       var sign = this.public_sign(ret);
       var xmlData = "<xml>";
        xmlData += "<mch_appid>" + ret.mch_appid + "</mch_appid>";
        xmlData += "<mchid>" + ret.mchid + "</mchid>";
        xmlData += "<nonce_str>" + ret.nonce_str + "</nonce_str>";
        xmlData += "<partner_trade_no>" + ret.partner_trade_no + "</partner_trade_no>";
        xmlData += "<openid>" + ret.openid + "</openid>";
        xmlData += "<check_name>" + ret.check_name + "</check_name>";
        xmlData += "<re_user_name>" + ret.re_user_name + "</re_user_name>";
        xmlData += "<amount>" + ret.amount + "</amount>";
        xmlData += "<desc>" + ret.desc + "</desc>";
        xmlData += "<spbill_create_ip>" + ret.spbill_create_ip + "</spbill_create_ip>";
        xmlData += "<sign>" + sign + "</sign>";
        xmlData += "</xml>";
        post.https_post3(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    },
    // 申请退款:需要证书
    wx_refund:function(transaction_id,out_refund_no,refund_fee,total_fee,cb){      
      // 推荐使用微信订单号：transaction_id
      if ((transaction_id == null || transaction_id == '') &&
          (out_refund_no == null || out_refund_no == '')){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
      var path = "/secapi/pay/refund";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          out_refund_no:out_refund_no,
          refund_fee:refund_fee,
          total_fee:total_fee,
          transaction_id:transaction_id,
          // out_trade_no:'',
          nonce_str:this.createNonceStr()
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<transaction_id>"+ret.transaction_id+"</transaction_id>"; //订单号
      // xmlData += "<out_trade_no>"+ret.out_trade_no+"</out_trade_no>"; //订单号
      xmlData += "<out_refund_no>" + ret.out_refund_no + "</out_refund_no>";
      xmlData += "<refund_fee>" + ret.refund_fee + "</refund_fee>";
      xmlData += "<total_fee>" + ret.total_fee + "</total_fee>";
      xmlData += "<sign>" + sign + "</sign>";
      // xmlData += "<sign_type>MD5</sign_type>";
      xmlData += "</xml>";
      // console.log(xmlData);
      post.https_post3(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          // console.log("222",ret,body);
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    },
    // 查询退款
    wx_refundquery:function(refund_id,cb){
      // 推荐使用微信的退款订单号：refund_id
      if (refund_id == null || refund_id == ''){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/pay/refundquery';
      var path = "/secapi/pay/refund";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          refund_id:refund_id,
          transaction_id:'',
          out_trade_no:'',
          out_refund_no:'',
          nonce_str:this.createNonceStr()
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<refund_id>" + ret.refund_id + "</refund_id>";
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<transaction_id>"+ret.transaction_id+"</transaction_id>"; //订单号
      xmlData += "<out_trade_no>"+ret.out_trade_no+"</out_trade_no>"; //订单号
      xmlData += "<out_refund_no>" + ret.out_refund_no + "</out_refund_no>";
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "</xml>";
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          console.log(body);
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    },
    // 下载对账单
    wx_downloadbill:function(bill_date,cb){
      // 推荐使用微信的退款订单号：refund_id
      if (bill_date == null || bill_date == ''){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/pay/downloadbill';
      var path = "/pay/downloadbill";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          bill_date:bill_date,//'20140603'
          bill_type:'ALL',
          tar_type:'',//是否压缩账单
          nonce_str:this.createNonceStr()
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<bill_date>"+ret.bill_date+"</bill_date>"; //订单号
      xmlData += "<bill_type>"+ret.bill_type+"</bill_type>"; //订单号
      xmlData += "<tar_type>" + ret.tar_type + "</tar_type>";
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "</xml>";
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          console.log(body);
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    },
    // 交易保障接口：https://api.mch.weixin.qq.com/payitil/report
    wx_report:function(interface_url,user_ip,cb){
      // 推荐使用微信的退款订单号：refund_id
      if ((interface_url == null || interface_url == '')&&
          (user_ip == null || user_ip == '')){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/payitil/report';
      var path = "/payitil/report";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          interface_url:interface_url,//'20140603'
          nonce_str:this.createNonceStr(),
          execute_time:1000,
          return_code:'SUCCESS',
          result_code:'SUCCESS',
          user_ip:user_ip
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<interface_url>"+ret.interface_url+"</interface_url>"; //订单号
      xmlData += "<execute_time>"+ret.execute_time+"</execute_time>"; //订单号
      xmlData += "<return_code>" + ret.return_code + "</return_code>";
      xmlData += "<result_code>" + ret.result_code + "</result_code>";
      xmlData += "<user_ip>" + ret.user_ip + "</user_ip>";
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "</xml>";
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          console.log(body);
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    },
    // 转换短连接:https://api.mch.weixin.qq.com/tools/shorturl
    wx_shorturl:function(long_url,cb){
      if (long_url == null || long_url == ''){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/pay/downloadbill';
      var path = "/pay/downloadbill";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          long_url:long_url,//'20140603'
          nonce_str:this.createNonceStr()
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<long_url>"+ret.long_url+"</long_url>"; //订单号
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "</xml>";
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          console.log(body);
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    },
    // 拉取订单评价数据接口：https://api.mch.weixin.qq.com/billcommentsp/batchquerycomment
    wx_batchquerycomment:function(begin_time,end_time,offset,cb){
      if ((begin_time == null || begin_time == '')&&
          (end_time == null || end_time == '') &&
          (offset == null || offset == '')){
          return;
      }
      var url = 'https://api.mch.weixin.qq.com/billcommentsp/batchquerycomment';
      var path = "/billcommentsp/batchquerycomment";
      var ret = {
          appid:wxconfig.appid,
          mch_id:wxconfig.mch_id,
          nonce_str:this.createNonceStr(),
          begin_time:begin_time,//'20140603'
          end_time:end_time,
          offset:offset
      };
      var sign = this.public_sign(ret);
      var xmlData = "<xml>";
      xmlData += "<appid>"+ret.appid+"</appid>"; //appid
      xmlData += "<mch_id>"+ret.mch_id+"</mch_id>"; //商户号
      xmlData += "<nonce_str>"+ret.nonce_str+"</nonce_str>"; //随机字符串，不长于32位
      xmlData += "<begin_time>"+ret.begin_time+"</begin_time>"; //订单号
      xmlData += "<end_time>"+ret.end_time+"</end_time>";
      xmlData += "<offset>"+ret.offset+"</offset>";
      xmlData += "<sign>" + sign + "</sign>";
      xmlData += "</xml>";
      post.https_post(xmlData,wxconfig.host,wxconfig.port,path,function(ret,body){
          console.log(body);
          if (ret == 200 && cb!=null){            
            cb(body,sign,ret);
          }
      });
    }   
};

module.exports = WxApi;


